package com.lxj.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lxj.constant.CategoryConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lxj.mapper.CategoryMapper;
import com.lxj.domain.Category;
import com.lxj.service.CategoryService;
import org.springframework.util.ObjectUtils;

/**
 * @author lxj
 * @date 2021/8/1 11:11
 * @Description: 
 */
@Service
@Slf4j
@CacheConfig(cacheNames = "com.lxj.service.impl.CategoryServiceImpl")
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService{

    @Autowired
    private CategoryMapper categoryMapper;

    /**
     * 查询商品分类
     *
     * @return
     */
    @Override
    @Cacheable(key = CategoryConstant.CATEGORY_PREFIX)
    public List<Category> list() {
        return categoryMapper.selectList(new LambdaQueryWrapper<Category>()
                .orderByDesc(Category::getSeq)
        );
    }

    /**
     * 查询商品所有的父分类
     *
     * @return
     */
    @Override
    @Cacheable(key = CategoryConstant.CATEGORY_PARENT_PREFIX)
    public List<Category> loadParentCategory() {
        return categoryMapper.selectList(new LambdaQueryWrapper<Category>()
                .eq(Category::getParentId, 0)
                .orderByDesc(Category::getSeq)
        );
    }

    /**
     * 新增分类
     *
     * @param category
     * @return
     */
    @Override
    @Caching(
            evict = {
                    @CacheEvict(key = CategoryConstant.CATEGORY_PREFIX),
                    @CacheEvict(key = CategoryConstant.CATEGORY_PARENT_PREFIX)
            }
    )
    public boolean save(Category category) {
        log.info("新增分类{}", JSON.toJSONString(category));
        category.setRecTime(new Date());
        category.setUpdateTime(new Date());
        category.setShopId(1L);
        Long parentId = category.getParentId();
        if (parentId == null || parentId.equals(0L)) {
            // 说明新增了一个跟级分类
            parentId = 0L;
            category.setGrade(1);
        } else {
            // 判断一下数据库有没有父分类
            Category parent = categoryMapper.selectById(parentId);
            if (ObjectUtils.isEmpty(parent)) {
                throw new IllegalArgumentException("新增时父分类不存在");
            }
            category.setGrade(2);
        }
        // 新增
        return categoryMapper.insert(category) > 0;
    }
}
